package com.xnyzc.lhy.order.common.pay;

import com.alibaba.fastjson.JSONObject;
import com.xnyzc.lhy.common.component.payment.ResponseHandler;
import com.xnyzc.lhy.common.component.payment.XmlUtil;
import com.xnyzc.lhy.common.constant.PayConstant;
import com.xnyzc.lhy.order.service.common.pay.IOaPaymentService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.jdom.JDOMException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Map;
import java.util.Objects;

/**
 * 微信支付回调通知
 *
 * @Author: 刘举
 * @Date: 2018/12/14 16:53
 */
@Api(description = "微信支付回调通知")
@Slf4j
@RestController
@RequestMapping("/oa/weChatPay")
public class WeChatPayNotify {

    @Value("${global.weChat.pay.appKey}")
    private String wxAppKey;

    @Autowired
    private IOaPaymentService iOaPaymentService;

    /**
     * weChatPay支付回调
     *
     * @param request
     * @param response
     */
    @PostMapping(value = "/weChatNotify")
    public void weChatNotify(HttpServletRequest request, HttpServletResponse response) {
        String inputLine;
        String notifyXml = "";
        try {
            while ((inputLine = request.getReader().readLine()) != null) {
                if (!"partner=&sign=&data=".equals(inputLine)) {
                    notifyXml += inputLine;
                }
            }
            request.getReader().close();

            Map<String, String> map = XmlUtil.doXMLParse(notifyXml);
            // 创建支付应答对象
            ResponseHandler resHandler = new ResponseHandler(request, response);
            resHandler.setKey(wxAppKey);

            // 验证通过
            if (resHandler.isTenpaySign(map)) {
                // 状态码验证
                String returnCode = map.get("return_code");

                // 返回成功
                if (Objects.equals(returnCode, PayConstant.WX_SUCCESS)) {

                    // 商户订单号
                    String outTradeNo = map.get("out_trade_no");
                    // 微信支付订单号
                    String transactionId = map.get("transaction_id");
                    // 订单号
                    String orderNo = outTradeNo.split("_")[0];
                    // 支付完成时间
                    String gmtPayment = map.get("time_end");
                    // 总费用
                    String totalAmount = map.get("total_fee");
                    // 业务结果
                    String resultCode = map.get("result_code");
                    // 回传参数
                    String attach = map.get("attach");
                    JSONObject jsonObject = JSONObject.parseObject(attach);

                    // 交易状态 0:交易失败 1：交易成功
                    Integer payStatus = -1;
                    if (Objects.equals(resultCode, PayConstant.WX_FAIL)) {
                        payStatus = 0;
                    } else if (Objects.equals(resultCode, PayConstant.WX_SUCCESS)) {
                        payStatus = 1;
                    }

                    log.info("商户订单号：{}", outTradeNo);
                    log.info("微信支付订单号：{}", transactionId);
                    log.info("订单号：{}", orderNo);
                    log.info("支付完成时间：{}", gmtPayment);
                    log.info("总费用：{}", totalAmount);
                    log.info("业务结果：{}", resultCode);
                    log.info("回传参数：{}", attach);

                    // 将微信回调的分为单位的金额转成已元为单位的金额
                    BigDecimal totalAmountB = new BigDecimal(totalAmount);
                    totalAmountB = totalAmountB.divide(new BigDecimal("100"));
                    totalAmount = totalAmountB.toString();

                    // 进行业务逻辑处理
                    iOaPaymentService.processAliPayNotify(payStatus, orderNo, transactionId, totalAmount, gmtPayment, jsonObject, 1);

                    resHandler.sendToCFT(PayConstant.RETURN_WX_MSG_SUCCESS);
                } else {
                    log.error("微信支付回调通知支付失败！");
                    resHandler.sendToCFT(PayConstant.RETURN_WX_MSG_FAIL);
                }
            } else {
                log.error("微信支付回调通知验证数据失败！");
                resHandler.sendToCFT(PayConstant.RETURN_WX_MSG_FAIL);
            }
        } catch (IOException e) {
            log.error("微信支付回调通知(IO流)处理异常！");
        } catch (JDOMException e) {
            log.error("微信支付回调通知(XML处理)异常！");
        }

    }
}
